﻿#include <iostream>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <sys/socket.h>

using std::cin;
using std::cout;
using std::endl;
using std::string;
#define CLIENT_IP "127.0.0.1"
#define CLIENT_PORT 12345
#define SERVER_IP "127.0.0.1"
#define SERVER_PORT 9999
#define BUF_SIZE 1024
void Error(const string &msg)
{
  cout << msg << endl;
  exit(-1);
}
int main()
{

  // step01:创建服务端套接字
  int sock_serv;
  if ((sock_serv = socket(PF_INET, SOCK_DGRAM, IPPROTO_UDP)) == -1)
    Error("socket() error!");
  cout << "socket() ok" << endl;
  sockaddr_in addr_serv{};
  addr_serv.sin_family = PF_INET;
  addr_serv.sin_addr.s_addr = inet_addr(SERVER_IP);
  addr_serv.sin_port = htons(SERVER_PORT);
  // step02:设置服务端套接字的iIP和端口
  if (bind(sock_serv, (sockaddr *)&addr_serv, sizeof(addr_serv)) == -1)
    Error("bind() error!");
  cout << "bind() ok ..." << endl;
  sockaddr_in addr_clnt{};
  socklen_t size_addr_clnt = sizeof(addr_clnt);
  char msg[BUF_SIZE];
  char response[BUF_SIZE];
  while (1)
  {
    if (recvfrom(sock_serv, msg, sizeof(msg), 0, (sockaddr *)&addr_clnt, &size_addr_clnt) != -1)
    {
      cout << "Message from client:" << msg << endl;
      strcpy(response, "ok");
      sendto(sock_serv, response, sizeof(response), 0, (sockaddr *)&addr_clnt, size_addr_clnt);
    }
  }
  close(sock_serv);
  return 0;
}